<template>
	<div class="page-wrapper">	
		<div style="height:8%; padding-bottom:var(--mPadding);">
			<div class="flex-btn large" @click="$router.push('/inspectionTask/manualTask')">
				<img :src="Icon1" />
				<span>手动生成巡检任务</span>
			</div>
			<el-popconfirm
    		    width="340px"
    		    confirm-button-text="确定"
    		    cancel-button-text="取消"
    		    title="此操作会删除所有自动生成的待执行任务（手动生成的任务不受影响），包括被编辑过的任务，请谨慎操作！"
    		    @confirm="handleRefresh"
    		>
    		    <template #reference>
    		        <div class="flex-btn large opacity">
						<img :src="Icon2" />
						<span>重新生成待执行任务</span>
					</div>
    		    </template>
    		</el-popconfirm>
			
		</div>
		<div style="height:92%">
			<TableWrapper :style="{ height:'100%' }" :controls="controls" :pageInfo="pageInfo" :sourceData="tableData" :column="column" :total="total"  @search="handleSearch" />
		</div>
		<!-- 新建巡检对象模板 弹窗 -->
		<TaskUpdateModal v-model:info="info" :userList="userList" @refresh="fetchTaskList" />
	</div> 
</template>

<script setup>
	import { reactive, onMounted, watch, computed, ref, h } from 'vue';
	import { useRouter, useRoute } from 'vue-router';
	import { useGlobalStore } from '@/stores/global';
	import { getTaskList, getUndealedTask, delTask } from '@/api/task.js';
	import { getGroupList, getUserList } from '@/api/group.js';
	import { getFieldAttrs } from '@/api/cycle.js';
	import { getTplList, getLabelList, getMeterTypeList, delTpl } from '@/api/tpl.js';
	import { ElMessage, ElPopconfirm, ElInput, ElLoading  } from 'element-plus'
	import TableWrapper from '@/components/TableWrapper/index.vue';
	import ConfirmDel from '@/components/ConfirmDel.vue';
	import TaskUpdateModal from './TaskUpdateModal.vue';
    import { formatDateTime } from '@/utils/date';
	import Icon1 from '@/assets/icon-add.png';
	import Icon2 from '@/assets/icon-refresh.png';

	const global =useGlobalStore();
	const router = useRouter();
	const route = useRoute();
	const tableData = ref([]);
	const total = ref(0);
	const userMaps = ref({});
	const userList = ref([]);
	const groupList = ref([]);
	const groupTotal = ref(0);
	const attrList = ref([]);
	const pageInfo = reactive({ page:1, pageSize:10 });
	const typeMaps = { 2:{ text:'巡检'}, 3:{ text:'点检'} };
	const controls = ref([
		{ type:'input', paramKey:'codeOrName', placeholder:'输入编号或名称查询' },
		{ type:'select', size:'small', paramKey:'groupId', payload:[], placeholder:'请选择分组', labelKey:'groupId', labelName:'groupName' },
		{ type:'select', size:'small', paramKey:'userId', payload:[], placeholder:'请选择负责人', labelKey:'userId', labelName:'userName' },
		{ type:'treeselect', paramKey:'attrId', fieldMaps:{ label:'attrName', value:'attrId', children:'subEnergyFieldAttr' }, payload:[], placeholder:'请选择位置' },
		{ type:'daterange', paramKey:'startTime', clearable:true },
		{ type:'select', paramKey:'missionStatus', placeholder:'请选择状态', payload:Object.keys(global.taskStatusMaps).map(key=>({ label:global.taskStatusMaps[key].text, key }))  },
		{ type:'select', paramKey:'missionCategory', placeholder:'请选择任务类型', payload:Object.keys(typeMaps).map(key=>({ label:typeMaps[key].text, key }))  }
	]);
	watch([groupList, userList, attrList], ()=>{
		controls.value[1] = { type:'select', paramKey:'groupId', payload:groupList.value, total:groupTotal.value, search:fetchGroupList, placeholder:'请选择分组', labelKey:'groupId', labelName:'groupName' };
		controls.value[2] = { type:'select', paramKey:'userId', payload:userList.value, total:userList.value.length, placeholder:'请选择负责人', labelKey:'userId', labelName:'userName' };
		controls.value[3] = { type:'treeselect', paramKey:'attrId', fieldMaps:{ label:'attrName', value:'attrId', children:'subEnergyFieldAttr' },  payload:attrList.value, placeholder:'请选择位置' };
	})
	
	const info = ref({ visible:false, forEdit:false });
	const actionMaps = {
        1:(row)=>[
			h('div', { onClick:()=>{ router.push({ path:'/inspectionTask/view', query:{ code:row.missionCode, page:pageInfo.page } }) }}, [h('i', { class:'ri-eye-line' }), h('span', null, '查看巡检项')]),
			h('div', { onClick:()=>{ info.value = { visible:true, forEdit:true, row } }}, [h('i', { class:'ri-eye-line' }), h('span', null, '编辑')]),
			h(ConfirmDel, { info:`确定要删除巡检任务${row.missionCode}吗？`, onConfirm:()=>{ handleDelete(row.missionCode) }} ),
		],
		2:(row)=>[
			h('div', { onClick:()=>{ router.push({ path:'/inspectionTask/view', query:{ code:row.missionCode } }) }}, [h('i', { class:'ri-eye-line' }), h('span', null, '查看巡检项')]),
		],
		3:(row)=>[
			h('div', { onClick:()=>{ router.push({ path:'/inspectionTask/execute', query:{ code:row.missionCode } }) }}, [h('i', { class:'ri-eye-line' }), h('span', null, '查看任务执行结果')]),
		],
		4:(row)=>[
			h('div', { onClick:()=>{ router.push({ path:'/inspectionTask/execute', query:{ code:row.missionCode } }) }}, [h('i', { class:'ri-eye-line' }), h('span', null, '查看任务执行结果')]),
		],
		5:(row)=>[
			h('div', { onClick:()=>{ router.push({ path:'/inspectionTask/view', query:{ code:row.missionCode } }) }}, [h('i', { class:'ri-eye-line' }), h('span', null, '查看巡检项')]),
			h(ConfirmDel, { info:`确定要删除巡检任务${row.missionCode}吗？`, onConfirm:()=>{ handleDelete(row.missionCode) }} ),
		],
	}
    const column = [
        { label:'编号', prop:'missionCode', width:'10%'  }, 
		{ label:'任务类型', hasTpl:true, width:'5%', render:row=>({ com:h('div', null, global.taskTypeMaps[row.missionCategory] ? global.taskTypeMaps[row.missionCategory].text : '--' ) }) },
		{ label:'开始推送时间', width:'8%', hasTpl:true, render:row=>{ const strArr = row.startTime.split('T'); return { com:h('div', null, strArr[0] || '--') }}},
		{ label:'任务截止时间', width:'8%', hasTpl:true, render:row=>{ const strArr = row.endTime.split('T'); return { com:h('div', null, strArr[0] || '--') }}},
		{ label:'巡检对象', width:'11%', prop:'targetName' },
		{ label:'对象信息', width:'27%', hasTpl:true, render:row=>{
			return {
				com:h('div', null, [
					h('span', null, `分组:${ row.groupName || '--' }`),
					h('span', { style:{ margin:'0 var(--sPadding)'}}, '/'),
					h('span', null, `位置:${ row.attrName || '--' }`),
					h('span', { style:{ margin:'0 var(--sPadding)'}}, '/'),
					h('span', null, `标签:${ row.labelName || '--' }`),
				])
			}
		}},
		{ label:'负责人', width:'6%', prop:'userName' },
		{ label:'状态', width:'6%', hasTpl:true, render:row=>{ const status = global.taskStatusMaps[row.missionStatus] || {}; return { com:h('span', { style:{ color:status.color } }, status.text || '未知')  }}},
        { label:'操作', width:'19%', hasTpl:true, render:(row)=>{
				return { com:h('div', { class:'action-container'}, actionMaps[row.missionStatus] ? actionMaps[row.missionStatus](row) : null ) };
        	}
		}
    ]; 	

	const handleSearch = (optional, pageInfo)=>{		
		fetchTaskList({ ...optional, ...pageInfo });
	}
	const handleDelete = (code)=>{
		delTask({ missionCode:code })
		.then(res=>{
			if ( res.data.code === 200 ) {
				ElMessage({
					type:'success',
					message:'删除巡检任务成功！' 
				});
				fetchTaskList();
			}
		})
	}
	const fetchTaskList = (params)=>{
		// 实际的axios请求;
		params = params || {};
		let realParams = { page:pageInfo.page, pageSize:pageInfo.pageSize };
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		const temp = realParams.startTime;
		if ( temp && temp.length && temp.length === 2 ) {
			let endTime = formatDateTime(temp[1], false) + ' 23:59:59';
			let startTime = formatDateTime(temp[0], false) + ' 00:00:00';
			realParams.startTime = startTime;
			realParams.endTime = endTime;
		}
		getTaskList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				tableData.value = res.data.data;
				total.value = res.data.total;
			}
		})
	};
	const fetchUserList = (params)=>{
		getUserList({})
		.then(res=>{
			if ( res.data.code === 200 ){
				if ( res.data.data ){
					let arr = []
					Object.keys(res.data.data).forEach(key=>{
						arr.push({ userId:key, userName:res.data.data[key] })
					});
					userMaps.value = res.data.data;
					userList.value = arr;
				}
			}
		})
	}
	// 请求维度属性
	const fetchFieldAttrs = ()=>{     
        getFieldAttrs()
        .then(res=>{
            if ( res.data.code === 200 ){
                attrList.value = res.data.data;          
            }
        })                                 
    }
	const fetchGroupList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:10 };
		getGroupList(params)
		.then(res=>{
			if ( res.data.code === 200 ){
				groupList.value = res.data.data;
				groupTotal.value = res.data.total;
			}
		})
	}
	// 重新生成待执行
	function handleRefresh(){
		const loading = ElLoading.service({
  		  lock: true,
  		  text: 'Loading',
  		  background: 'rgba(0, 0, 0, 0.7)',
  		})
		getUndealedTask()
		.then(res=>{
			if ( res.data.code === 200 ){
				ElMessage({
					type:'success',
					message:'重新生成待执行任务成功！'
				})
				fetchTaskList();
				loading.close();
			}
		})
	}
	onMounted(()=>{
		if ( route.query.page ) {
			pageInfo.page = Number(route.query.page);
		} 
		fetchTaskList();
		fetchUserList();
		fetchGroupList();
		fetchUserList();
		fetchFieldAttrs();
	})
	
</script>
